package io.knifer.gokexceltask.service.impl;

import com.google.common.io.Files;
import io.knifer.gokexceltask.excel.handler.StudentDataExcelHandler;
import io.knifer.gokexceltask.service.StudentService;
import io.knifer.gokexceltask.utils.HttpUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service
@AllArgsConstructor
public class StudentServiceImpl implements StudentService {
    private final StudentDataExcelHandler studentDataExcelHandler;

    @Override
    public Map<String, String> saveByExcel(MultipartFile file, boolean allowMiscDataAutoInsert) throws IOException {
        Map<String, List<String>> validateMsg = new ConcurrentHashMap<>();
        String fileName = file.getOriginalFilename();
        String suffix = Files.getFileExtension(fileName);
        File dest = File.createTempFile(UUID.randomUUID().toString(), suffix);

        file.transferTo(dest);
        HttpUtils.setSessionAttr("validate_msg", validateMsg);

        return studentDataExcelHandler.importByExcel(dest, allowMiscDataAutoInsert);
    }

    @Override
    public UUID exportStudentDataAsExcel() throws IOException {
        UUID fileName = UUID.randomUUID();

        studentDataExcelHandler.exportAsExcel(fileName);

        return fileName;
    }

    @Override
    public UUID exportAndMockStudentDataAsExcel(int rows) throws IOException {
        UUID fileName = UUID.randomUUID();

        studentDataExcelHandler.mockAsExcel(fileName, rows);

        return fileName;
    }
}
